/*****目标团队--靶标 --攻防赛*****/
<template><!---->
	<search-table
	    ref="searchTable"
		:columns="targetTeamCol"
		:data="targetTeamData"
		:total="targetTeamTotal"
		:page.sync="queryTargetTeamInfo.pageIndex"
		:size.sync="queryTargetTeamInfo.pageSize"
		:disabled = "(data) => {
			data.targetVisibility == 1
		}"
		showSelectTag
		:selection.sync="selectTargetTeams"
		@change-size="getTargetSize"
		@change-page="getTargetPage"
	>
	<Alert type="warning" show-icon v-if="[8, 9].includes(type)" slot="alert">
		<p style="color:#f90">未分配的题目禁止切换是否显示的状态</p>
	</Alert>
	<template slot="search">
		<!-- <Checkbox v-model="selectAll" @on-change="handleCheckAll" :disabled="disSelectAll()" v-if="[8, 9].includes(type)" style="margin-right:15px;">全选</Checkbox> -->
		<Button
			type='primary' 
			ghost 
			style="margin-right:15px;"
			v-if="configMode !== 1"
			@click="aotoGenarateTargets('')" 
			:disabled="disabledAllBtn"><img src="../../../../assets/scene/auto-target-allot-purple.png" alt="" />一键配置</Button>
		<Button
			v-if="configMode !== 1 && [8, 9].includes(type)"
			type="primary"
			ghost
			:disabled="disabledAllBtn || progress == 4"
			title="添加题目"
			@click="showAddAndUpdate()"
			style="margin-right:15px;">添加题目</Button>
		<Button 
			v-if="[8, 9].includes(type)"
			type="primary" 
			ghost
			:disabled="disBatchShowBtn() || targetTeamTotal < 1" 
			@click="batchShow" 
			style="margin-right:15px;">批量显示</Button>
		<Select filterable v-model="queryTargetTeamInfo.isFixedFileFlag" style="width:150px;margin-right:15px;" v-if="[8, 9].includes(type)"
			@on-change="getTargetPage(1)" clearable placeholder="请选择验证类型">
			<Option value="1">静态Flag</Option>
			<Option value="0">固定Flag</Option>
			<Option value="2" v-if="type === 9">Checker</Option>
			<Option value="3" v-if="type !== 8">提交报告</Option>
		</Select>
	</template>
	<Modal v-model="targetModal.show"
      	:title="targetModal.title"
      	:loading = "targetModal.loading"
      	width="600px"
      	:mask-closable = "false"
      	@on-cancel="handleReset('formValidate')"
		@on-visible-change="$refs.formValidate.resetFields()"
      	@on-ok="saveTargetTeam">
		<Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100" v-if="targetModal.type == '1'">
		<Alert type="warning" show-icon>
			<p style="color:#f90" v-if="type !== 8">确认添加题目后，系统将自动部署已选题目，并返回竞赛列表页面。</p>
			<p style="color:#f90" v-else>确认添加题目后，当存在使用新的模板镜像的题目时，系统将自动部署已选题目，并返回竞赛列表页面。</p>
		</Alert>
          <FormItem label="题目" prop="ids">
            <Select filterable v-model="formValidate.ids" placeholder="请选择题目" filterable multiple>
              <Option  v-for="question in challsDataPageOption" :value="question.id"  :key="question.id" :title="question.name">{{question.name}}</Option>
            </Select>
          </FormItem>
        </Form>
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100" v-if="targetModal.type == '2'">
          <!--1:攻防赛，渗透演练需要题目-->
		  <!-- 修改时不允许修改题目，如果要允许，要考虑公用一个虚拟机模板的题目都会被查询出来的问题 -->
		  <FormItem  label="是否显示" prop="targetVisibility" v-if="[8, 9].includes(type)" key="targetVisibility">
            <RadioGroup v-model="formValidate.targetVisibility">
              <Radio :label="1">是</Radio>
              <Radio :label="0">否</Radio>
            </RadioGroup>
          </FormItem>
		  <Row v-if="[8,9].includes(type) && formValidate.targetVisibility === 0 && routeParams.path!=='攻防赛'" key="timeDisplay">
			<Col span="4">
				<FormItem label="定时显示">
					<Checkbox v-model="formValidate.timer" @on-change="setTime" style="line-height:32px;"></Checkbox>
				</FormItem>
			</Col>
			<Col span="14">
				<FormItem label="显示时间：">
					<!--:options = "timeOptions"-->
					<DatePicker v-model="formValidate.showTime"
							placeholder="请选择显示时间"
							type="datetime"
							style="width: 200px"
							:editable="false"
							format="yyyy-MM-dd HH:mm"
							v-if="formValidate.timer"
							@on-change="changeTime($event)"
					></DatePicker>
					<span class="error-text" v-show="showErrorText">{{errorText}}</span>
				</FormItem>
			</Col>
		  </Row>
          <FormItem label="题目" prop="questionId">
            <Select filterable v-model="formValidate.questionId" placeholder="请选择题目" @on-change="setTeamQuestion" filterable disabled>
              <Option  v-for="question in showQuestionList" :value="question.id"  :key="question.chaId"
			  	 :title="`${question.type == 'target' ? '[漏洞靶标库]':'[主观题题库]'}${question.name}`">{{question.type == 'target' ? '[漏洞靶标库]':'[主观题题库]'}}{{question.name}}</Option>
            </Select>
          </FormItem>
          <FormItem  label="题目显示名称" prop="name">
            <Input v-model.trim="formValidate.name" placeholder="题目显示名称" disabled></Input>
          </FormItem>
          <!--<FormItem label="靶标类型" prop="type" @on-change="formValidate.path == ''">
            <RadioGroup v-model="formValidate.type">
              <Radio :label=0>flag</Radio>
              <Radio :label=1>多个虚拟机flag相同</Radio>
              <Radio :label=2>多个虚拟机flag不同</Radio>
              <Radio :label=3 >文档</Radio>
            </RadioGroup>
          </FormItem>-->
          <!--<FormItem label="所属团队" prop="teamId">
            <Select filterable  v-model="formValidate.teamId" placeholder="请选择团队" @on-change="changeTeamGroup">
              <Option  v-for="item in accessGroupList" :value="item.id"  :key="item.id">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="子网" prop="subnet">
            <Select filterable  v-model="formValidate.subnet" placeholder="请选择子网" @on-change="changeSubnet">
              <Option  v-for="item in subnetList" :value="item.id"  :key="item.id">{{item.name}}</Option>
            </Select>
          </FormItem>
          <FormItem label="虚拟机" prop="vmId" v-show="formValidate.questionId">
            <Select filterable v-model="formValidate.vmId" placeholder="请选择虚拟机" filterable @on-change="changeVm" ref="vmSelect">
              <Option v-for="item in vmlists" :value="item.id" :key="item.id">{{item.name}}</Option>
            </Select>
          </FormItem>-->
          <FormItem label="分值" prop="score">
            <InputNumber :min="0" :max="1000" v-model="formValidate.score" placeholder="请输入分值"></InputNumber>
            <span style="color:#f90">
            	<Icon type="ios-information-circle-outline" />
            	本靶标的基础分
            </span>
          </FormItem>

          <Row v-if="routeParams.path!=='攻防赛' && false">
            <Col span="4">
              <FormItem label="定时显示" >
                <Checkbox v-model="formValidate.timer" @on-change="setTime" style="line-height:32px;"></Checkbox>
              </FormItem>
            </Col>
            <Col span="14">
              <FormItem label="显示时间：">
                <!--:options = "timeOptions"-->
                <DatePicker v-model="formValidate.showTime"
                            placeholder="请选择显示时间"
                            type="datetime"
                            style="width: 200px"
                            :editable="false"
                            format="yyyy-MM-dd HH:mm"
                            v-if="formValidate.timer"
                            @on-change="changeTime($event)"
                ></DatePicker>
                <span class="error-text" v-show="showErrorText">显示时间不得早于当前时间</span>
              </FormItem>
            </Col>
          </Row>
          <!--<FormItem  label="是否显示" prop="visibility">
            <RadioGroup v-model="formValidate.visibility">
              <Radio :label=1>显示</Radio>
              <Radio :label=0>不显示</Radio>
            </RadioGroup>
            <span style="color:#f90"> <Icon type="ios-information-circle-outline" />用于在演练页面的展示控制</span>
          </FormItem>-->
          <!--渗透需要题目顺序-->
          <!--<FormItem  label="排序" prop="sequence" v-if="type == 4 && stMode == 0">
            <InputNumber v-model="formValidate.sequence" :min="1" placeholder="请输入排序"></InputNumber>
          </FormItem>-->
          <FormItem  label="Flag路径" prop="flagPath" v-if="formValidate.isFixedFileFlag === '1'">
            <Input v-model.trim="formValidate.flagPath" placeholder="请输入路径"></Input>
          </FormItem>
          <!--<FormItem label="flag路径" prop="path" v-if="formValidate.type == 0 && pathList.length > 0">
            <Select filterable v-model="formValidate.path" placeholder="请输入路径">
              <Option v-for="path in pathList" :value="path.addresses[0].applyFlagUrl" :key="path.id">{{path.addresses[0].applyFlagUrl}}</Option>
            </Select>
          </FormItem>-->
          <!--<FormItem  label="访问方式" prop="access">
            <RadioGroup v-model="access" @on-change="changeAccess">
              <Radio label="1">内网访问</Radio>
              <Radio label="2">映射访问</Radio>
            </RadioGroup>
          </FormItem>-->
          <FormItem  label="内网IP" prop="ip">
            <Input v-model.trim="formValidate.ip" placeholder="请输入IP" style="width:300px" disabled></Input>
          </FormItem>
          <FormItem  label="内网访问端口" prop="port" v-if="type !== 8">
            <Input v-model.trim="formValidate.port" placeholder="请输入PORT(1~65535)" style="width:300px" disabled></Input>
          </FormItem>
          <FormItem  label="内网服务端口" prop="servicePort" v-if="type !== 8">
            <Input v-model.trim="formValidate.servicePort" placeholder="请输入PORT(1~65535)" style="width:300px"></Input>
          </FormItem>
		  <FormItem  label="攻击端口" prop="servicePort" v-if="scoringType == 1 && type === 8">
            <Input v-model.trim="formValidate.servicePort" placeholder="请输入PORT(1~65535)" style="width:300px"></Input>
          </FormItem>
          <FormItem  label="防守端口" prop="defensivePort" v-if="scoringType == 1 && type === 8">
            <Input v-model.trim="formValidate.defensivePort" placeholder="请输入PORT(1~65535)" style="width:300px"></Input>
          </FormItem>
          <FormItem  label="外网访问端口" prop="externalPort" v-if="![8, 9].includes(type)">
            <Input v-model.trim="formValidate.externalPort" placeholder="请输入PORT(1~65535)" style="width:300px"></Input>
          </FormItem>
          <FormItem  label="外网服务端口" prop="externalServicePort" v-if="![8, 9].includes(type)">
            <Input v-model.trim="formValidate.externalServicePort" placeholder="请输入PORT(1~65535)" style="width:300px"></Input>
          </FormItem>
		  <FormItem  label="脚本" prop="scriptId" v-if="[9].includes(type) && formValidate.isFixedFileFlag === '2'" key="script-id">
			<Select filterable v-model="formValidate.scriptId" placeholder="请选择脚本" filterable key="script-select">
				<Option v-for="item in checkerList"
					:key="item.id"
					:value="item.id"
					@mouseenter.native="mouseOverConfiger($event,item.id)"
					@mouseleave.native="mouseLeaveConfiger($event,item.id)"
					@click.stop.prevent="configurationInformation=false">{{item.name}}</Option>
			</Select>
			<div v-show="configurationInformation" :style="{position:'absolute',left:cardPanelLeft,top:cardPanelTop,zIndex:'9999999999999999',}" 
				@mouseenter="jinru" @mouseleave="yichu" @click.stop.prevent>
				<Card :style="{minWidth:'350px',maxWidth:'600px'}"  >
					<p slot="title" style="position:relative">
						<Icon type="ios-construct"></Icon>
						{{configPanel.configName}}
						<span slot="title" style="position:absolute;right:0px">
						<Icon type="ios-contact"></Icon>
						{{configPanel.configCreatorName}}
					</span>
					</p>
					<ul>
						<li><span class="_dot"></span>path：{{configPanel.configPath}}</li>
						<li><span class="_dot"></span>argArr：{{configPanel.configArg}}</li>
						<li><span class="_dot"></span>cmd：{{configPanel.configCmd}}</li>
						<li><span class="_dot"></span>sysType：{{configPanel.configSystype}}</li>
						<li><span class="_dot"></span>protocol：{{configPanel.protocol}}</li>
						<li><span class="_dot"></span>serverPort：{{configPanel.serverPort}}</li>
						<li><span class="_dot"></span>language：{{configPanel.language}}</li>
						<li><span class="_dot"></span>CreateTime：{{configPanel.configCreateTime}}</li>
						<li><span class="_dot"></span>Desc：{{configPanel.configDescription}}</li>
					</ul>
				</Card>
			</div>
          </FormItem>
		  <FormItem label="防守源码" prop="deFileName" v-if="scoringType == 1">
			<item-upload
			  ref="deFileUpload"
			  @upload-success="changeDeFile"
			  @del-item="deleteDeFile"
			  @upload-loading="handleFileUploading"
			  :allFileType="true"
			  btnTxt="源码"
			  :isSingle="true"
			  :isConfirm="false"
			  :fileList="deFileList"
			></item-upload>
			<!-- fileType="docs" -->
			<!-- :formatArr="['txt']" -->
		  </FormItem>
          <FormItem  label="描述" prop="description" key="description">
            <Input type="textarea" disabled :maxlength="200" v-model.trim="formValidate.description" placeholder="描述" key="description-textarea"></Input>
          </FormItem>
          <!--<FormItem  label="访问跳转IP" prop="externalIp" v-if="access == '2'">
            <Input v-model.trim="formValidate.externalIp" placeholder="请输入IP"></Input>
          </FormItem>
          <FormItem  label="跳转端口" prop="externalPort" v-if="access == '2'">
            <Input v-model.trim="formValidate.externalPort" placeholder="请输入PORT(1~65535)" style="width:300px"></Input>
          </FormItem>-->
        </Form>
      </Modal>
	<Modal v-model="tagsModal"
      	title="提示信息"
      	width="800px"
      	:mask-closable = "false"
      	footer-hide>
        <ctfTag :target="curTarget" v-if="tagsModal" :sceneInfo="sceneInfo"></ctfTag>
    </Modal>
</search-table>
</template>

<script>
  import {getTargetTeamList_new,addAndAllocationTarget,modifyTargetTeam_new,delTargetTeam_new, autoAllotTopoTarget,
    getSceneInfo,queryVmWithParty,aotoGenarateTargets,updataFlagServePath,ctfQuestionIncrement,changeTargetVisibility} from '@/api/drill_compete'
  import {queryCtfList} from '@/api/question'
  import {getFlagServerList,loadConfiguration,queryTargetList} from '@/api/drill'
  import {getaccessgrouplist} from '@/api/access_new'
  import { getNumReg } from '@/libs/reg'
  import ctfTag from './ctfTag.vue'
  import ItemUpload from '@/components/item-upload';
  import { encode, decode, sceneStatusEscape, format } from '@/libs/utils'
	export default {
    name: 'scenes',
    props:['type','disabledAllBtn','configMode','progress'],
    components:{ctfTag,ItemUpload},
	inject: ['detailParent'],
	data(){
		const validateNum = (rule, value, callback) => { //只能填入数字
	      	var reg = new RegExp("^([1-9]|[1-9]\\d|100)$");
	      	//验证警戒值
	      	if(value){
	      		if (!reg.test(value)) {
	      			callback(new Error('请输入1-100的整数'));
	      		}else{
	      			callback()
	      		}
	      	}else{
	      		callback()
	      	}
	      }
		  const validatePort = (rule, value, callback) => { //验证只能填入数字
	      	var reg = new RegExp("^(([1-9]\\d{0,3})|([1-5]\\d{4})|(6[0-4]\\d{3})|(65[0-4]\\d{2})|(655[0-2]\\d)|(6553[0-5]))$");
	      	//验证警戒值
	      	if(value){
	      		if (!reg.test(Number(value))) {
	      			callback(new Error('请输入1-65535的整数'));
	      		}else{
	      			callback()
	      		}
	      	}else{
	      		callback()
	      	}
	      }
	      const validateIP = (rule, value, callback) => { //验证只能填入数字
	      	var reg = new RegExp("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
	      	//验证警戒值
	      	if(value){
	      		if (!reg.test(value)) {
	      			callback(new Error('ip格式错误'));
	      		}else{
	      			callback()
	      		}
	      	}else{
	      		callback()
	      	}
	      }
	  	return {
			checkerList: [], // checker列表
			configurationInformation: false,
			hoverCdraBol: false,
			showErrorText: false,
			cardPanelLeft:'3px',
			cardPanelTop:'3px',
			errorText: '',
			configPanel:{
				configPath:'',
				configSystype:'',
				configContent:'',
				configDescription:'',
				configCreateTime:'',
				configCreatorName:'',
				configName:'',
				configType:'',
				configArg:'',
				configCmd:'',
				protocol:'',
				serverPort:'',
				language:'',
			},
			routeParams:{
      path:this.$route.query.path,
			id:this.$route.query.id,
			prjid:this.$route.query.prjid
			},
			targetModal:{
				show:false,
				title:'',
				loading:true,
				type:1 //1添加，2修改
			},
			pathList:[],
	//		accessGroupList:[],
	//      vmlists:[],
	//      teamlists:[],
			queryTargetTeamInfo:{
				pageIndex:1,
				pageSize:10,
				sceneId:this.$route.query.id,
				projectId:this.$route.query.prjid,
				isFixedFileFlag: ''
			},
			questionList:[],
			access:'1',
			formValidate: {
				timer: false,
				showTime: '',
				ids: [],
				targetVisibility: 0,
			//"createTime": "2020-02-10T03:35:50.081Z",
			//"creator": "string",
			"scriptId": '',
			"description": "", //描述
			"externalIp": "", //对外ip
			"externalPort": "", //对外端口
			//"ip": "string",
			"name": "", //题目显示名称
			//"password": "string",
			"port": "",
			"projectId": this.$route.query.prjid,
			"questionId": '', //题目id
			"sceneId": this.$route.query.id,
			"score": 0,
			//"status": 0, //状态：1 正常/防护成功，2 被攻破，3 服务异常，4 被攻破+服务异常
			//"teamId": "",
			//"teamName": "",
			"type": 0, //靶标类型：0.单个虚拟机、1.多个虚拟机flag相同、2.多个虚拟机flag不同、3.文件类型
			//"user": "string",
			"visibility": 0, //可见性：是否可见- 0.不可见 1可见
			//"vmId": "",
			"flagPath":"/opt/flag.txt",
			"sequence":1,
			"servicePort":"",
			deFile:null
			},
			deFileList:[],
			fileUploading:false,
			oldFormValidate:{},
			ruleValidate: {
				ids:[
					{ required: true, type:'array',min:1,message: '题目不能为空', trigger: 'change' }
				],
				targetVisibility:[
					{ required: true,type:'number',message: '请选择', trigger: 'change'}
				],
				name: [
					{ required: true, message: '名字不能为空', trigger: 'change' }
				],
				scriptId: [
					{ required: true, message: '请输入脚本', trigger: 'change' }
				],
			type: [
				{ required: true,type:'number',message: '请选择靶标类型', trigger: 'change' },
			],
			score:[
				{ required: true, type:'number',message: '请输入分值', trigger: 'change'},
				{ validator: getNumReg(1000), trigger: 'change' }
			],
			sequence:[
				{ required: true, type:'number',message: '请输入排序', trigger: 'change'},
				{ validator: validateNum, trigger: 'change' }
			],
	//        path:[
	//          { required: true ,message: '请输入路径', trigger: 'change'}
	//        ],
	//        externalIp:[
	//        	{ required: true, message: '请输入对外IP', trigger: 'change'}
	//        ],
	//        externalPort:[
	//        	{ required: true, type:'number',message: '请输入对外端口', trigger: 'change'}
	//        ],
			questionId:[
				{ required: true, message: '请选择题目', trigger: 'change'}
			],
			ip:[
				{ validator: validateIP, trigger: 'change' }
			],
			port:[
				{ validator: validatePort, trigger: 'change' }
			],
			servicePort:[
				// { required:true, message:'请输入端口'},
				{ validator: validatePort, trigger: 'change' }
			],
			defensivePort:[
				{ required:true, message:'请输入端口'},
				{ required:true,validator: validatePort, trigger: 'change' }
			],
			externalPort:[
				{ validator: validatePort, trigger: 'change' }
			],
			externalServicePort:[
				{ validator: validatePort, trigger: 'change' }
			],
	//        externaIp:[
	//        	{ validator: validateIP, trigger: 'change' }
	//        ]
	//        visibility:[
	//        	{ required: true, type:'number',message: '请选择', trigger: 'change'}
	//        ],
	//        vmId:[
	//        	{ required: true, message: '请选择虚拟机', trigger: 'change'}
	//        ],
	//        teamId:[
	//        	{ required: true, message: '请选择团队', trigger: 'change'}
	//        ],
			},
			initTargetObjData:{
			"createtime": "",
			"createuser": localStorage.getItem('username'),
			"frequency": 0,
			"id": "",
			"isshow": 1,
			"lastupdatetime": "",
			"modifier": "",
			"sceneid": "",
			"targetdes": "",
			"targetname": "",
			"targetsubmittype":0,
			"targettype": 0,
			"teamid": "",
			"type": 0,
			"uri": "",
			"vmid": "",
			"score":'0'
			},
			querytime:{},
			targetTeamCol:[
			{
				type: 'selection',
				width:60,
				align:'center',
				placement:'top-left',
				show: [8, 9].includes(this.type)
				// render:(h,params) => {
				// 	return h('Checkbox',{
				// 		props:{
				// 			value:params.row._checked,
				// 			disabled:params.row.targetVisibility == 1
				// 		},
				// 		on:{
				// 			'on-change':(e) => {
				// 				this.selectSingle(e,params.row);
				// 			}
				// 		}
				// 	})
				// }
			},
			{
				title:'题目显示名称',
				key:'name',
				align:'center',
				ellipsis:true,
				tooltip:true,
				width: 240,
				placement:'top-left'
	//          width:100
			},
			{
				title:'内网IP',
				key:'ip',
				align:'center',
				ellipsis:true,
				width:112
			},
			{
				title:'内网访问端口',
				key:'port',
				align:'center',
				ellipsis:true,
				width:50,
				show:() => {
					return this.type !== 8
				}
			},
			{
				title:'内网服务端口',
				key:'servicePort',
				align:'center',
				ellipsis:true,
				width:50,
				show:() => {
					return this.type !== 8
				}
			},
			{
				title:'攻击端口',
				key:'servicePort',
				align:'center',
				ellipsis:true,
				width:50,
				show:() => {
					return this.scoringType == 1 && this.type === 8
				}
			},
			{
				title:'防守端口',
				key:'defensivePort',
				align:'center',
				ellipsis:true,
				width:50,
				show:() => {
					return this.scoringType == 1 && this.type === 8
				}
			},
			{
				title:'外网访问端口', // 删除外网访问端口、外网服务端口列的展示
				key:'externalPort',
				align:'center',
				ellipsis:true,
				width:50,
				show:(data) => {
					return ![8, 9].includes(this.type)
				}
			},
			{
				title:'外网服务端口', // 删除外网访问端口、外网服务端口列的展示
				key:'externalServicePort',
				align:'center',
				ellipsis:true,
				width:50,
				show:(data) => {
					return ![8, 9].includes(this.type)
				}
			},
			{
				title: 'Flag',
				key: 'flag',
				align: 'left',
				tooltip: true,
				// minWidth: 60,
				show: () => {
					return [8, 9].includes(this.type)
				}
			},
			{
				title: '验证方式',
				key: 'isFixedFileFlag',
				align: 'left',
				tooltip: true,
				// minWidth: 60,
				filter: this.flagTypeFilter,
				show: () => {
					return [8, 9].includes(this.type)
				}
			},
			{
				title: '脚本',
				key: 'scriptId',
				align: 'left',
				tooltip: true,
				// minWidth: 60,
        render:(h,params) => {
          let checklist = this.checkerList||[]
          let name = ''
          let sid = params.row.scriptId+''
          checklist.forEach(item=>{
            if(sid===(item.id+'')){
              name = item.name
            }
          })
          return h('span',{},name)
        },
				show: () => { //运维赛
					return this.type === 9
				}
			},
			{
				title: '是否显示', // 只有攻防plus需要展示定时显示时间
				key: 'targetVisibility',
				align: 'left',
				tooltip: true,
				// minWidth: 60,
				//filter: this.targetVisibilityFilter,
        render:(h,params) => {
          return h('span',{},params.row.targetVisibility == '1' ? '是' : '否' )
        },
				show: () => {
					return [8,9].includes(this.type)
				}
			},
			{
				title: '定时显示时间', // 只有攻防plus需要展示定时显示时间
				key: 'showTime',
				align: 'left',
				tooltip: true,
				// minWidth: 60,
				filter: this.showTimeFilter,
				show: () => {
					return [8,9].includes(this.type)
				}
			},
			{
				title:'路径',
				key:'flagPath',
				align:'center',
				tooltip:true,
				width:120
			},
			{
				title:'分值',
				key:'score',
				align:'center',
				ellipsis:true,
				tooltip:true,
				placement:'top-right',
				width:60
			},
			{
				type:'link',
				key:'deFileName',
				title:'防守源码',
				tooltip:true,
				setPath:(data) => {
					return `/api/minio/download?path=${data.deFilePath}`
				},
				show:() => {
					return this.scoringType == 1
				}
			},
			{
				title:'描述',
				key:'description',
				align:'center',
				ellipsis:true,
				tooltip:true,
				width: 200
			},
			{
				title:'操作',
				key:'action',
				ellipsis:true,
				width:180,
				placement:'top-right',
				opList:[
					{
						txt:'修改',
						type:'modify',
						disabled:() => {
                          return this.disabledAllBtn
                        },
						fun:this.showAddAndUpdate
					},
					{
						txt: '提示',
						show: () => {
							return [8, 9].includes(this.type);
						},
						disabled: () => {
							return this.disabledAllBtn;
						},
						fun: (data) => {
							this.curTarget = data;
							this.tagsModal = true;
						}
					},
					{
						type:'delete',
						txt:'删除',
						disabled:() => {
                          return this.disabledAllBtn
                        },
						fun:(data) => {
							this.delTargetTeam(data.id)
						},
						show:() => {
							return this.configMode !== 1 && [8, 9].includes(this.type)
						},
						tooltip:true,
						title:'确认删除？'
					}
				],
				// render:(h,params)=>{
				// 	return h('div',[
				// 	h('Button',{
				// 	props:{
				// 		type:'text',
				// 		size:'small',
				// 		disabled:this.disabledAllBtn
				// 	},
				// 	attrs:{
				// 		title:'修改'
				// 	},
				// 	style:{
				// 		border:'none',
				// 		background:'none',
				// 		boxShadow:'none',
				// 	},
				// 	on:{
				// 		click:()=>{
				// 		this.showAddAndUpdate(params.row)
				// 		}
				// 	}
				// 	},[
				// 		h('img', {
				// 		attrs: {
				// 			src:this.disabledAllBtn ? require('../../../../assets/project/modifys.png') : require('../../../../assets/project/modifys-h.png')
				// 		},
				// 		style: {
				// 			cursor: 'pointer',
				// 			'vertical-align': 'middle',
				// 			display:'inline-block',
				// 			marginBottom:'4px',
				// 		},
				// 	}),
				// 	]),
				// 	h('Poptip', {
				// 		props: {
				// 			confirm: true,
				// 			'ok-text': "确定",
				// 			'cancel-text': "取消",
				// 			type: 'error',
				// 			size: 'large',
				// 			title: '你确定要删除吗?',
				// 			transfer:true
				// 		},
				// 		on: {
				// 			'on-ok': () => {
				// 				this.delTargetTeam(params.row.id)
				// 			}
				// 		}
				// 	}, [
				// 		h('Button', {
				// 			props: {
				// 				type: 'text',
				// 				size: 'small',
				// 				disabled:this.disabledAllBtn
				// 			},
				// 			attrs:{
				// 				title:'删除'
				// 			},
				// 			style: {
				// 				border:'none',
				// 				background:'none',
				// 				boxShadow:'none',
				// 				display: this.configMode !== 1 && [8, 9].includes(this.type) ? 'inline-block' : 'none'
				// 			},
				// 		}, [
				// 			h('img', {
				// 				attrs: {
				// 					src:this.disabledAllBtn ? require('../../../../assets/project/delNote-d.png') :
				// 						require('../../../../assets/project/delNote-h.png')
				// 				},
				// 				style: {
				// 					cursor: 'pointer',
				// 					'vertical-align': 'middle',
				// 					display:'inline-block',
				// 					marginBottom:'4px',
				// 				},
				// 			}),
				// 			h('span',{
				// 				style: {
				// 					cursor: 'pointer',
				// 					color:'#2d8cf0'
				// 				},
				// 			})
				// 		])
				// 	])
				// ])
				// }
				}
			],
			allTargetTeamData: [],
			selectTargetTeams:[],
			targetTeamData:[],
			targetTeamTotal:0,
			TargetId:'',
	//      subnetList:[],
	//      subnet:''
			sceneInfo:{},
			stMode:0,
			allVms:[],
			targetList:[],
			flagServerList: [],
			challsDataPage: [],
			curTarget: {},
			tagsModal: false,
			selectAll: false,
	  	}
	},
	filters:{

	},
	computed:{
		challsDataPageOption() {
			let questionIds = this.allTargetTeamData.map(item => item.questionId)
			let ret = []
			if (questionIds.length) {
				ret = this.challsDataPage.filter(item => !questionIds.includes(item.id))
			} else {
				ret = this.challsDataPage
			}
			return ret.filter(item => item.answers.length < 2)
		},
		showQuestionList(){
			let quesList = [];
			this.questionList.forEach(ques => {
				if(this.vmImages.includes(ques.imageId)){
					ques.type = 'question';
					ques.id = ques.chaId;
					quesList.push(ques)
				}
			})
			this.targetList.forEach(target => {
				if(this.vmImages.includes(target.imageId)){
					target.type = 'target';
					target.id = target.targetId;
					target.name = target.targetName;
					quesList.push(target)
				}
			})
			return quesList;
		},
		vmImages() {
			return [...new Set(this.allVms.map(vm => vm.imageId))]
		},
		scoringType() {//0  混合计分模式  1单独计分模式
			return this.detailParent.scoringType || 0;
		}
	},
	async mounted(){
		await this.getFlagServer()
    	//this.getAllSence()
    	//this.getAllTargetHost();
//  	this.getProjectInfo();
//  	this.getAccessGroupList();
    	await this.getAllVmlist(true);
        getSceneInfo(this.$route.query.id).then(data => {
        	if(data.code == 1){
        		this.sceneInfo = data.data;
        		this.stMode = JSON.parse(data.data.extension).stMode;
        		if(this.stMode == 0){
        			this.targetTeamCol.splice(0, 0,{
			            title:'排序',
			            key:'sequence',
			            align: 'center',
			            ellipsis:true,
			            width:100
		            });
        		}
        	}
        });
		if ([8, 9].includes(this.type)) { // 删除外网访问端口、外网服务端口列的展示
			// let index = this.targetTeamCol.findIndex(item => item.title === '外网访问端口')
			// if (index !== -1) {
			// 	this.targetTeamCol.splice(index, 1)
			// }
			// index = this.targetTeamCol.findIndex(item => item.title === '外网服务端口')
			// if (index !== -1) {
			// 	this.targetTeamCol.splice(index, 1, {
			// 		title:'Flag',
			// 		key:'flag',
			// 		align:'center',
			// 		tooltip:true,
			// 		width:120
			// 	}, {
			// 		title:'验证方式',
			// 		key:'isFixedFileFlag',
			// 		align:'center',
			// 		tooltip:true,
			// 		width:120,
			// 		render:(h,params)=>{
            //   			return h('span',this.flagTypeFilter(params.row.isFixedFileFlag))
			// 		}
			// 	})
			// }
			// if (this.type === 9) {
			// 	index = this.targetTeamCol.findIndex(item => item.title === '验证方式')
			// 	if (index !== -1) {
			// 		this.targetTeamCol.splice(index, 0, {
			// 			title: '脚本',
			// 			key:'scriptName',
			// 			align:'center',
			// 			ellipsis:true,
			// 			tooltip:true,
			// 			width: 200
			// 		})
			// 	}
			// }
			// 只有攻防plus需要展示定时显示时间
			// if (this.type === 8) {
			// 	index = this.targetTeamCol.findIndex(item => item.title === '验证方式')
			// 	if (index !== -1) {
			// 		this.targetTeamCol.splice(index, 0, {
			// 			title:'是否显示',
			// 			key:'isFixedFileFlag',
			// 			align:'center',
			// 			ellipsis:true,
			// 			tooltip:true,
			// 			placement:'top-right',
			// 			render:(h,params) => {
			// 				return h('Tag',{
			// 					props:{
			// 					color:params.row.targetVisibility == '1' ? 'success' :'default',
			// 					type:"border"
			// 					},
			// 					on:{
			// 						click:()=>{

			// 						}
			// 					}
			// 				},params.row.targetVisibility == '1' ? '是' : '否' )
			// 			}
			// 		}, {
			// 			title:'定时显示时间',
			// 			align:'center',
			// 			ellipsis:true,
			// 			tooltip:true,
			// 			placement:'top-right',
			// 			render: (h, params) => {
			// 				return h('span', {
			// 					style: {
			// 						width: '140px',
			// 						display: 'inline-block'
			// 					}
			// 				}, params.row.showTime ? params.row.showTime : '-')
			// 			}
			// 		})
			// 	}
			// }
			// index = this.targetTeamCol.findIndex(item => item.title === '操作')
			// if (index !== -1) {
			// 	this.targetTeamCol.splice(index, 1, {
			// 		title:'操作',
			// 		key:'os',
			// 		ellipsis:true,
			// 		width:200,
			// 		placement:'top-right',
			// 		action:true,
			// 		render:(h,params)=>{
			// 			return h('div',[
			// 				h('Button',{
			// 					props:{
			// 						type:'text',
			// 						size:'small',
			// 						disabled:this.disabledAllBtn
			// 					},
			// 					attrs:{
			// 						title:'修改'
			// 					},
			// 					style:{
			// 						border:'none',
			// 						background:'none',
			// 						boxShadow:'none',
			// 					},
			// 					on:{
			// 						click:()=>{
			// 							this.showAddAndUpdate(params.row)
			// 						}
			// 					}
			// 				},[
			// 					h('img', {
			// 						attrs: {
			// 							src:this.disabledAllBtn ? require('../../../../assets/project/modifys.png') : require('../../../../assets/project/modifys-h.png')
			// 						},
			// 						style: {
			// 							cursor: 'pointer',
			// 							'vertical-align': 'middle',
			// 							display:'inline-block',
			// 							marginBottom:'4px',
			// 						},
			// 					}),
			// 				]),
			// 				h('Button',{
			// 					props:{
			// 						type:'text',
			// 						size:'small',
			// 						disabled:this.disabledAllBtn
			// 					},
			// 					attrs:{
			// 						title:'提示'
			// 					},
			// 					style:{
			// 						border:'none',
			// 						background:'none',
			// 						boxShadow:'none',
			// 					},
			// 					on:{
			// 						click:()=>{
			// 							this.curTarget = params.row;
			// 							this.tagsModal = true;
			// 						}
			// 					}
			// 				},[
			// 					h('Icon', {
			// 						props: {
			// 							type: "md-bulb",
			// 							size: 26
			// 						},
			// 						style: {
			// 							'margin-top': '-4px',
    		// 							'margin-right': '4px',
			// 							color: this.disabledAllBtn ? '#8F90A6' : '#3D52C9'
			// 						}
			// 					}),
			// 				]),
			// 				h('Poptip', {
			// 					props: {
			// 						confirm: true,
			// 						'ok-text': "确定",
			// 						'cancel-text': "取消",
			// 						type: 'error',
			// 						size: 'large',
			// 						title: '你确定要删除吗?',
			// 						transfer:true
			// 					},
			// 					on: {
			// 						'on-ok': () => {
			// 							this.delTargetTeam(params.row.id)
			// 						}
			// 					}
			// 				}, [
			// 					h('Button', {
			// 						props: {
			// 							type: 'text',
			// 							size: 'small',
			// 							disabled:this.disabledAllBtn
			// 						},
			// 						attrs:{
			// 							title:'删除'
			// 						},
			// 						style: {
			// 							border:'none',
			// 							background:'none',
			// 							boxShadow:'none',
			// 							display: this.configMode !== 1 && [8, 9].includes(this.type) ? 'inline-block' : 'none'
			// 						},
			// 					}, [
			// 						h('img', {
			// 							attrs: {
			// 								src:this.disabledAllBtn ? require('../../../../assets/project/delNote-d.png') :
			// 									require('../../../../assets/project/delNote-h.png')
			// 							},
			// 							style: {
			// 								cursor: 'pointer',
			// 								'vertical-align': 'middle',
			// 								display:'inline-block',
			// 								marginBottom:'4px',
			// 							},
			// 						}),
			// 						h('span',{
			// 							style: {
			// 								cursor: 'pointer',
			// 								color:'#2d8cf0'
			// 							},
			// 						})
			// 					])
			// 				])
			// 			])
			// 		}
			// 	})
			// }
		}
		if (this.type === 9) { // 运维赛需要查询脚本列表
			await this.getCheckerList()
		}
		// if (![8, 9].includes(this.type)) {
		// 	let index = this.targetTeamCol.findIndex(item => item.key === 'select')
		// 	if (index !== -1) {
		// 		this.targetTeamCol.splice(index, 1)
		// 	}
		// }
    	this.queryCtfQuestionList();
    	this.getTargetTeamList();
    	this.queryTargetList();
	},
    methods:{
		// 获取配置的checkerList
		getCheckerList() {
			return new Promise(resolve => {
				loadConfiguration({
					pageSize: 2147483646,
					type: 'vulnerability'
				}).then(({code, data, message}) => {
					if (code === 1) {
						this.checkerList = data.items
					} else {
						if (message) {
							this.$Message.warning(message)
						}
					}
				}).finally(() => {
					resolve()
				})
			})
		},
		jinru(){
			this.hoverCdraBol = true
		},
		yichu(){
			this.hoverCdraBol = false
			this.configurationInformation = false
			this.cardPanelLeft = '0'
			this.cardPanelTop = '0'
		},
		mouseLeaveConfiger(ev,value){
			clearTimeout(this.optionOutEvent)
			this.optionOutEvent = setTimeout(() => {
				if(!this.hoverCdraBol){
					this.configurationInformation = false
					this.cardPanelLeft = '0'
					this.cardPanelTop = '0'
				}
			}, 300);
		},
		mouseOverConfiger(e,value){
			clearTimeout(this.optionHoverEvent)
			this.optionHoverEvent = setTimeout(() => {
				if(this.hoverCdraBol){
					return;
				}
				this.configurationInformation = true
				this.cardPanelLeft = e.layerX +30+ 'px'
				this.cardPanelTop = e.layerY +35+'px'
				//查询配置详细信息
				let template = this.checkerList.find(item => {
					return item.id === value
				})
				if (template) {
					this.configPanel.configName = template.name
					this.configPanel.configPath = template.path
					this.configPanel.configSystype = template.sysType
					this.configPanel.configArg = template.argArr
					this.configPanel.configCmd = template.cmd
					this.configPanel.protocol = template.protocol
					this.configPanel.serverPort = template.serverPort
					this.configPanel.language = template.language
					this.configPanel.configDescription = template.description
					this.configPanel.configCreateTime = template.createTime
					this.configPanel.configCreatorName = template.creatorName
				}
			}, 300);
		},
		// 判断传入的时间字符串是否在当前时间之前
		isBeforeTimestamp(dataStr) {
			return new Date(dataStr) <= new Date()
		},
		changeTime(time){
			this.showErrorText = this.isBeforeTimestamp(time)
			if (this.showErrorText) {
				this.errorText = '显示时间不得早于当前时间'
			}
		  	this.formValidate.showTime = time;
			if (!time) {
				this.showErrorText = true
				this.errorText = '请设置显示时间'
			}
		},
		// 默认一小时后展示
	    setTime(timer){
	    	this.formValidate.timer = timer;
			if (!this.formValidate.showTime) {
				let timeStr = format(new Date(new Date().getTime() + 3600000), 'yyyy-MM-dd hh:mm')
				this.formValidate.showTime = timeStr;
			}
			if (!timer) {
				this.showErrorText = timer
			}
		},
		// disSelectAll() {
		// 	return this.targetTeamData.every(target => target.targetVisibility == 1)
		// },
		disBatchShowBtn(){
			return this.selectTargetTeams.length === 0
		},
		batchShow(){
			changeTargetVisibility(this.$route.query.id, this.selectTargetTeams.map(item => {
				return {
					id: item.id,
					targetVisibility: 1
				}
			})).then(({ code, message }) => {
				if (code !== 1) {
					this.$Message.warning(message)
					return
				}
				this.$Message.success('批量显示成功')
				this.selectTargetTeams = [];
				this.getTargetTeamList()
			})
		},
		handleCheckAll(e){
			this.selectAll = e;
			this.targetTeamData.forEach(target => {
				this.selectSingle(e,target);
			})
		},
		selectSingle(e,target){
			if(target.targetVisibility == 0){
				this.$set(target,'_checked',e);
			}
			if(this.targetTeamData.filter(target => target.targetVisibility == 0).every(target => target._checked === true)){
				this.selectAll = true;
			}else{
				this.selectAll = false;
			}
		},
		flagTypeFilter(val){
	      let str = '未定义类型';
	      switch (val) {
	      	case '0':str = '固定Flag';break;
	        case '1':str = '静态Flag';break;
	        case '2':str = 'Checker';break;
	        case '3':str = '提交报告';break;
	        default:break;
	      }
	      return str;
	    },
		getFlagServer() {
			return new Promise(resolve => {
				getFlagServerList({
					page: 1,
					pageSize: 2147483646,
                    projectId:this.$route.query.prjid,
                    ip: '192.168.18'
				}).then(({ code, message, data = {} }) => {
					if (code !== 1) {
						this.$Message.warning(message)
					} else {
						this.flagServerList = data.list || []
					}
				}).catch(() => {
					this.$Message.error('获取Flag服务器列表异常')
				}).finally(() => {
					resolve()
				})
			})
		},
    	initData(){
			this.deFileList = [];
    		this.formValidate = {
				timer: false,
				showTime: '',
				ids: [],
				targetVisibility: 0,
	          //"createTime": "2020-02-10T03:35:50.081Z",
			  //"creator": "string",
			  "scriptId": '',
			  "description": "", //描述
			  "externalIp": "", //对外ip
			  "externalPort": "", //对外端口
			  //"ip": "string",
			  "name": "", //题目显示名称
			  //"password": "string",
			  "port": "",
			  "projectId": this.$route.query.prjid,
			  "questionId": '', //题目id
			  "sceneId": this.$route.query.id,
			  "score": 0,
			  //"status": 0, //状态：1 正常/防护成功，2 被攻破，3 服务异常，4 被攻破+服务异常
//			  "teamId": "",
//			  "teamName": "",
			  "type": 0, //靶标类型：0.单个虚拟机、1.多个虚拟机flag相同、2.多个虚拟机flag不同、3.文件类型
			  //"user": "string",
			  "visibility": 0, //可见性：是否可见- 0.不可见 1可见
//			  "vmId": "",
			  "flagPath":"/opt/flag.txt",
			  "sequence":1,
			  "servicePort":'',
//			  "subnet":"",
				deFile:null
	        }
    	},
//  	getProjectInfo(){
//			getstatusbyprjid(this.$route.query.prjid).then(data => {
//				if(data.code == 1){
//					this.projectInfo = data.attribute;
//				}
//			})
//		},
        aotoGenarateTargets(){
			if (!this.allTargetTeamData.length) {
				this.$Message.warning('请先添加题目，再进行一键配置')
				return
			}
            aotoGenarateTargets(this.$route.query.id).then(data => {
                if(data.code==1){
                    if (this.flagServerList.length > 0) { // 存在Flag服务器，需要重新配置Flag路径
                        getTargetTeamList_new({
                            pageIndex: 1,
                            pageSize: 2147483646,
                            sceneId: this.$route.query.id,
                            projectId: this.$route.query.prjid
                        }).then(({ code, message, data = {} }) => {
                            if (code !== 1) {
                                this.$Message.warning(message)
                            } else {
                                let applyFlagUrl = this.flagServerList[0].addresses[0].applyFlagUrl
                                let list = data.items || []
                                if (list.length) {
                                    updataFlagServePath(list.map(item => {
                                        let vm = this.allVms.find(subItem => subItem.imageId === item.imageId)
                                        return {
                                            id: item.id,
                                            flagPath: vm.sysType==='windows' ? `${applyFlagUrl}/html`: applyFlagUrl
                                        }
                                    })).then(({ code, message }) => {
                                        if (code !== 1) {
                                            this.$Message.warning(`靶标自动新建成功，但${message}，无法重设Flag服务器路径`)
                                            this.getTargetTeamList();
                                        } else {
                                            this.aotoGenarateTargetsIsSuccee()
                                        }
                                    }).catch(() => {
                                        this.$Message.error('靶标自动新建成功，但重设Flag服务器路径异常')
                                        this.getTargetTeamList();
                                    })
                                } else {
                                    this.aotoGenarateTargetsIsSuccee()
                                }
                            }
                        }).catch(() => {
                            this.$Message.error('靶标自动新建成功，但查询竞赛题目异常，无法重设Flag服务器路径')
                            this.getTargetTeamList();
                        })
                    } else {
                        this.aotoGenarateTargetsIsSuccee()
                    }
                }else{
                    this.$Message.warning(data.message);
                }
            }).catch(error => {
            })
        },
        aotoGenarateTargetsIsSuccee() {
            // 分配成功后清空搜索条件，回退到首页
            this.queryTargetTeamInfo.pageIndex = 1
            this.getTargetTeamList();
            this.$Message.info("靶标自动新建成功！");
            autoAllotTopoTarget(this.$route.query.id).then(({ code, message }) => {
                if (code !== 1) {   
                    this.$Message.warning(`${message}， 请手动分配`)
                }
            }).catch(() => {
                this.$Message.warning('自动分配题目异常， 请手动分配')
            })
        },
		queryCtfList() {
			queryCtfList({
				category: '',
				flagType: "",
				matchMode: this.type === 8 ? '4' : "",
				name: "",
				needEnv: 1
			}, {
				pageIndex: 1,
				pageSize: 2147483646,
			}).then(data => {
				if (data.code == 1) { //新接口查询主观题原chaId变为id，needEnv字段查询时候需要，但返回无此字段用是否有镜像代替是否需要环境。保持页面原有逻辑
					this.challsDataPage = data.data.items;
				}
			})
		},
    	showAddAndUpdate(info){
    		this.initData();
    		this.targetModal.show = true;
    		if(!info){
    			this.targetModal.title = '添加题目';
    			this.targetModal.type = 1;
    			this.access = "1";
                this.queryCtfList()
    		}else{
    			this.targetModal.title = '修改题目';
    			this.targetModal.type = 2;
    			this.formValidate = JSON.parse(JSON.stringify(info));
				if (this.formValidate.showTime) {
					this.$set(this.formValidate, 'timer', true)
				}
    			this.question = {imageId:this.formValidate.imageId};
  			    if(this.formValidate.externalPort || this.formValidate.externalIp ){
  				    this.access = "2";
  			    }else{
  				    this.access = "1";
  			    }
				if(info.deFileName){
					this.deFileList = [
						{
							id: '',
							fileName: info.deFileName,
							path: info.deFilePath
						}
					];
				}
    		}
    	},
	  	addTargetTeam(){
	  		// 添加题目
			let projectId = this.$route.query.prjid
			let sceneId = this.$route.query.id
			let ids = this.formValidate.ids
			let targetVisibility = 0
			let list = this.challsDataPage.filter(item => ids.includes(item.id))
			let params = list.map(item => {
				return {
					"description": item.description, //描述
					"externalIp": "", // 对外ip
					"externalPort": "", // 对外端口
					"name": item.name, //题目显示名称
					"port": item.port,
					"projectId": projectId,
					"questionId": item.id, //题目id
					"sceneId": sceneId,
					"score": item.score,
					"type": 1,
					"visibility": 0, //可见性：是否可见- 0.不可见 1可见
					"flagPath": item.flagPath,
					"servicePort": item.port,
					"isNeedSubmitFlag": item.flagType === '2' ? '2' : String(item.submitFlag),
					"isFixedFileFlag": String(item.flagType),
					"flag": item.flagTxt,
					"imageId": item.imageId,
					"imageName": item.imageName,
					fileId: item.attachmentId,
					fileName: item.attachmentName,
					filePath: item.attachmentPath,
					targetVisibility,
					defensivePort: this.type === 8 ? item.defensivePort : undefined,
					isExistTips: (item.attachmentName && String(item.attachmentName).trim() !== '') ? 1 : 0,
				}
			})
			list = list.map(item => {
				return {
					"flavorRef": item.flavorRef,
					"imageRef": item.imageId,
					"name": item.name
				}
			})
			let progress = sceneStatusEscape(this.progress)
			ctfQuestionIncrement(sceneId, list, {
				competitionStatus: progress
			}).then(res => {
				if (res.code !== 1) {
					this.$Message.warning(res.message)
					this.cancelLoading('targetModal');
				} else {
					addAndAllocationTarget(sceneId, params).then(({ code, message }) => {
						if (code !== 1) {
							this.$Message.warning(message)
							this.cancelLoading('targetModal');
							return
						}
						if (this.type !== 8) {
							this.$Message.success('题目添加成功，增量部署中...');
							this.$router.push(`${this.type === 8 ? '/awdPlusContest' : 'opContest'}`)
						} else {
							if (list.some(item => !this.vmImages.includes(item.imageRef))) { // 使用了新的虚拟机，需要提示增量部署，并跳转页面
								this.$Message.success('题目添加成功，增量部署中...');
								this.$router.push(`${this.type === 8 ? '/awdPlusContest' : 'opContest'}`)
							} else { // 不需要重新部署，停留在当前页，刷新数据即可
								this.$Message.success('题目添加成功');
								this.targetModal.show = false
								this.getTargetPage(1)
								this.getAllVmlist(true)
							}
						}
					}).catch((error) => {
						this.$Message.error('添加题目异常')
						this.cancelLoading('targetModal');
					})
				}
			}).catch((error) => {
				this.$Message.error('添加题目异常')
				this.cancelLoading('targetModal');
			})
	  	},
	  	modifyTargetTeam(){
	  		let params = JSON.parse(JSON.stringify(this.formValidate));
	  		params.questionName = this.question.name;
			changeTargetVisibility(this.$route.query.id, [{
				id: params.id,
				targetVisibility: params.targetVisibility
			}]).then(({ code, message }) => {
				if (code !== 1) {
					this.$Message.warning(message)
					return
				}
				if (params.timer) { // 没设置显示时间，不传递这个参数
					if (typeof this.formValidate.showTime === 'object') { // 奇怪这个参数有时就是个时间戳，需要转义一下
						params.showTime = `${format(this.formValidate.showTime, 'yyyy-MM-dd hh:mm')}:00`
					} else {
						params.showTime = `${this.formValidate.showTime}:00`
					}
				} else {
					params.showTime = ''
				}
				if (typeof this.formValidate.showTime === 'object') {
					this.formValidate.showTime.getTime
				}
				modifyTargetTeam_new(params).then(data => {
					if(data.code==1){
						this.getTargetTeamList();
						this.$Message.success('修改成功');
						this.handleReset('formValidate');
						this.targetModal.show = false;
					}else{
						this.cancelLoading('targetModal');
					}
				}).catch(error => {
					this.$Message.error('修改异常')
					this.cancelLoading('targetModal');
				})
			})
	  	},
	  	saveTargetTeam(){
			if(this.fileUploading){
				this.$Message.info('请等待文件上传完成');
				return 
			}
	  		this.$refs['formValidate'].validate((valid) => {
	            if (valid) {
					if (!this.showErrorText) {
						if(this.targetModal.type == 1){
							this.addTargetTeam();
						}else{
							this.modifyTargetTeam();
						}
					} else {
						this.cancelLoading('targetModal');
					}
	            }else{
	            	this.cancelLoading('targetModal');
	            }
	        })
	  	},
	  	getTargetTeamList(){
        let _this = this

      
	  		getTargetTeamList_new(this.queryTargetTeamInfo).then(data => {
	  			if(data.code==1){
					let list = data.data.items || data.data || []
					this.selectAll = false
	  				this.targetTeamData = list.map(item => {
						if (item.scriptId) {
							if (this.type === 9) {
								let template = this.checkerList.find(subItem => {
									return subItem.id === item.scriptId
								})
								if (template) {
									item.scriptName = template.name
								}
							}
						}
						return item
					})
	  				this.targetTeamTotal = data.data.total;
	  			}else{

	  			}
	  		})
			getTargetTeamList_new({ // 顺便需要查询一次全部数据，用于比对添加题目时，哪些题目不可选
				pageIndex:1,
				pageSize: 2147483646,
				sceneId:this.$route.query.id,
				projectId:this.$route.query.prjid
			}).then(({ code, data }) => {
				if (code === 1) {
					this.allTargetTeamData = data.items || []
				}
			})
	  	},
	  	delTargetTeam(id){
	  		delTargetTeam_new(id).then(data => {
	  			if(data.code==1){
                  // 删除后展示当前页，当前页没有数据展示前一页
                  this.queryTargetTeamInfo.pageIndex = (this.targetTeamData.length == 1 && this.queryTargetTeamInfo.pageIndex > 1) ?
                          this.queryTargetTeamInfo.pageIndex - 1 : this.queryTargetTeamInfo.pageIndex;
	  				this.getTargetTeamList();
					this.$Message.info('删除成功');
	  			}else{
					this.$Message.warning(data.message);
	  			}
	  		}).catch(error => {
	  			this.$Message.error('删除异常');
	  		})
	  	},
	  	cancelLoading(name){
	    	this[name].loading = false;
	      	setTimeout(() => {
	      		this[name].loading = true;
	      	})
	    },
	    typeFilter(val){
	      let str = '';
	      switch (val) {
	      	case 0:str = 'Flag';break;
	        case 1:str = '多个虚拟机Flag相同';break;
	        case 2:str = '多个虚拟机Flag不同';break;
	        case 3:str = '文档';break
	        default:break;
	      }
	      return str;
	    },
	    getAllVmlist(setAll){
	        let params = {
				page:1,
				pageSize:10000,
				sortBy:'name',
				order:'asc',
				findPorts:true,
				vmType:'TEST'
			}
			if ([8, 9].includes(this.type)) { // 攻防赛plus，题目的类型为SERVER
				params.vmType = 'SERVER'
			}
	        if(this.question){
	        	params.imageId = this.question.imageId;
	        }
            return new Promise(resolve => {
                queryVmWithParty(this.routeParams.prjid,params).then(data => {
                    if(data.code == 1){
                        if(setAll){
                            this.allVms = data.data.list || data.data;
                        }else{
                            let vmlists = data.data.list || data.data;
                            let vm = vmlists.filter(vm => vm.imageId == this.question.imageId);
                            if(vm.length > 0){
                                this.formValidate.ip = vm[0].address[0].ips[0].ipAddress;
                                this.formValidate.name = vm[0].name;
                            }
                        }
                    }
                }).finally(() => {
					resolve()
				})
            })
	    },
//	    getAccessGroupList(){
//			if(!this.routeParams.id){
//				return;
//			}
//			let params = {
//				pageIndex:1,
//				pageSize:2147483647,
//				testId:this.routeParams.id
//			};
//			this.selectGroupList = [];
//			getaccessgrouplist(params).then(data => {
//				if(data.code == 1){
//					this.accessGroupList = data.data.items;
//				}else if(data.code == -2) {
//					this.accessGroupList = [];
//				}else{
//					this.$Message.warning(data.message);
//				}
//			})
//		},
	    getTargetSize(size){
	      this.queryTargetTeamInfo.pageSize = size;
	      this.getTargetTeamList()
	    },
	    getTargetPage(page){
	      this.queryTargetTeamInfo.pageIndex = page;
	      this.getTargetTeamList()
	    },
	    setTeamQuestion(val){
	    	if(!val){
	    		return
	    	}
	    	this.question = this.showQuestionList.filter(question => question.id == val)[0];
	    	if(this.question.type == 'question'){
		    	this.formValidate.servicePort = this.question.port;
		    	this.formValidate.score = this.question.score;
		    	this.formValidate.imageId = this.question.imageId;
		    	this.formValidate.imageName = this.question.imageName;
		    	this.formValidate.flagPath = this.question.flagPath || '/opt/flag.txt';
		    	//this.formValidate.name = this.question.name;
		    	this.formValidate.description = this.question.description;
		    	this.formValidate.vmId = '';
	    	}else if(this.question.type == 'target') {
	    		this.question = this.showQuestionList.filter(target => target.id == val)[0];
	    		this.formValidate.servicePort = this.question.openPort;
	    		this.formValidate.description = this.question.description;
	    		this.formValidate.imageId = this.question.imageId;
	    		this.formValidate.flagPath = this.question.flagPath || '/opt/flag.txt';
		    	this.formValidate.imageName = this.question.imageName;
	    		this.formValidate.vmId = '';
	    	}
	    	this.getAllVmlist();
	    },
//	    changeTeamGroup(val){
//	    	this.formValidate.vmId = '';
//	    	if(!val){
//	    		return
//	    	}
//	    	this.setTeamGroup(val);
//	    },
//	    setTeamGroup(val){
//	    	if(!val){
//	    		return
//	    	}
//	    	this.group =  this.accessGroupList.filter(group => group.id == val)[0];
//	    	this.formValidate.teamName = this.group.name;
//	    	this.getAllVmlist();
//	    },
//	    changeSubnet(){
//	    	this.formValidate.vmId = '';
//	    	this.getAllVmlist();
//	    },
	    handleReset (name) {
	      //this.$refs[name].resetFields();
	//    this.addTarget = false;
	        this.initData();
			this.$refs.deFileUpload && this.$refs.deFileUpload.cancelUpload();
	        this.$refs [name].fields.forEach(function (e) {
			      if (e.fieldValue != undefined && e.fieldValue!='') {
			          e.resetField()
			      }
			})
	    },
	    queryCtfQuestionList(){//查询ctf题列表-不分页--需要环境
	        let obj = {
	          pageIndex:1,
	          pageSize:2147483647,
	          isNeedEnv:'1',
	          //visibility:'share',
	          //isNeedSubmitFlag:'1',
	          //category:this.autoPro.ctfType.join(',')
	        };
	        let _this = this;
	        queryCtfList(obj).then(data => {
	          if(data.code == 1){
	            _this.questionList = data.data.items.filter(ques => ques.imageId) || data.data;
	          }else{
	            _this.$Message.warning(data.message);
	          }
	        })
	    },
	    queryTargetList(){
	    	let params = {
	    		page:1,
	            rows:2147483647,
	    	};
	        queryTargetList(params).then(data => {
	          if(data.code == 1){
	            this.targetList = data.attribute.data;
	          }else{
	            this.$Message.warning(data.message);
	          }
	        })
        },
	    changeVm(id){
	    	this.formValidate.path = '';
	    	this.getVmIp(id);
	    },
	    getVmIp(id){
	    	if(id){
	    		let server = this.vmlists.filter(vm => vm.id == id)[0];
	    		this.getFlagServerList(server.address[0].ips[0].ipAddress);
	    		//this.getFlagServerList(server.addresses[0].ip);
	    	}
	    },
	    getFlagServerList(ip){
	    	let curIp = ip.split('.').slice(0,3).join('.');
	    	let params = {
	    		page:1,
	    		pageSize:1000,
	    		projectId:this.$route.query.prjid,
	    		ip:curIp
	    	}
	    	getFlagServerList(params).then(data => {
	    		if(data.code == 1){
	    			//this.pathList = data.data.list;
	    			if(data.data.list.lenth > 0){
	    				this.formValidate.path = data.data.list[0].addresses[0].applyFlagUrl;
	    			}
	    		}
	    	})
	    },
	    changeAccess(access){
//	    	if(access == "1" && this.targetModal.type == 2){
//	    		this.formValidate.externalPort = this.oldFormValidate.externalPort;
//    			this.formValidate.externalIp = this.oldFormValidate.externalIp;
//	    	}else if(access == "2" && this.targetModal.type == 2){
//	    		this.formValidate.port = this.oldFormValidate.port;
//	    	}
	    },
//	    getProjectSubnet(){
//	    	queryNetworkList(this.$route.query.prjid,this.projectInfo.network.id).then(data => {
//	    		if(data.code == 1){
//	    			let subnetList = [];
//	    			data.attribute.editorStage.childs.forEach(item => {
//	    				subnetList = subnetList.concat(item.childs);
//	    			})
//	    			this.subnetList = subnetList;
//	    		}
//	    	})
//	    }
		changeDeFile(file) {
			this.formValidate.deFileName = file.fileName
			this.formValidate.deFilePath = file.filePath
			this.deFileList = [
				{
					id: file.fileId,
					fileName: file.fileName,
					path: file.filePath
				}
			];
		},
		deleteDeFile() {
			this.deFileList = [];
			this.formValidate.deFileName = ''
			this.formValidate.deFilePath = ''
		},
		handleFileUploading(status) {
			this.fileUploading = status;
		},
  }
}
</script>

<style>
  .drillsTable .ivu-poptip-body {
    text-align: left!important;
  }
  .scenesHeader{
    margin-bottom: 16px;
  }
  .drillTables{
    min-height: 300px;
  }
  .drillsTable.ivu-table-wrapper{
    overflow: inherit;
  }
</style>
<style scoped>
  .targetHeader{
    /*padding: 10px;*/
    margin: 15px 0;
  }
  .error-text {
	  color: #ed4014;
	  display: inline-block;
  }
</style>
